﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Configuration;
using Quartz;
using Anay.TaskScheduling.Job;

namespace Anay.TaskScheduling.Common
{
    public class JobFactory
    {
        private IJob job = null;

        public JobFactory()
        {
            string settings = ConfigurationManager.AppSettings["JobInfo"].ToString();
            var isLoadExternalModule = bool.Parse(ConfigurationManager.AppSettings["isLoadExternalModule"].ToString());
            if (isLoadExternalModule)
            {
                if (!string.IsNullOrWhiteSpace(settings))
                {
                    JobInfo jobInfo = new JobInfo();
                    Type t = jobInfo.GetType();

                    //获取相关配置 
                    var settingSplit = settings.Split(';');

                    //遍历赋值
                    foreach (var item in settingSplit)
                    {
                        var itemSplit = item.Split('=');
                        t.GetProperty(itemSplit[0]).SetValue(jobInfo, itemSplit[1]);
                    }

                    //加载程序集
                    Assembly assembly = Assembly.LoadFrom(jobInfo.DllPath);

                    job = assembly.CreateInstance(jobInfo.ClassName) as IJob;
                }
            }
            //默认实例BaseJob
            if (job == null)
                job = new BaseJob();
        }

        public IJob GetInstance()
        {
            return job;
        }
    }
    
    //job相关信息
    public class JobInfo
    {
        //程序集路径
        public string DllPath { get; set; }
        public string ClassName { get; set; }
    }
}
